
from pynput.keyboard import Controller as KeyboardController, Key
from pynput.mouse import Button, Controller as MouseController
import pygetwindow as gw
import time

def activate_window(title):
    """激活指定标题窗口"""
    windows = gw.getWindowsWithTitle(title)
    if not windows:
        print(f"未找到窗口: {title}")
        return None
    window = windows[0]
    window.restore()
    time.sleep(1)
    window.activate()
    time.sleep(1)
    print(f"已激活窗口: {title}")
    return window

keyboard = KeyboardController()
mouse = MouseController()
def press_key( key_str: str, time_keep: float = 0.05):
    """
    支持：
    - 普通键: 'a', '1', 'space'
    - 特殊键: 'f10', 'enter', 'esc'
    - 组合键: 'alt+right', 'ctrl+shift+s'
    """
    try:
        # 解析组合键
        parts = key_str.lower().split('+')
        keys = []

        for part in parts:
            part = part.strip()
            if part in ['ctrl', 'control']:
                keys.append(Key.ctrl)
            elif part in ['alt']:
                keys.append(Key.alt)
            elif part in ['shift']:
                keys.append(Key.shift)
            elif part in ['enter']:
                keys.append(Key.enter)
            elif part in ['cmd', 'command', 'win']:
                keys.append(Key.cmd)
            elif part.startswith('f') and part[1:].isdigit():
                f_num = int(part[1:])
                if 1 <= f_num <= 12:
                    keys.append(getattr(Key, f'f{f_num}'))
            elif hasattr(Key, part):
                keys.append(getattr(Key, part))
            else:
                # 普通字符
                keys.append(part)

        # 按下所有键
        for k in keys:
            keyboard.press(k)
        time.sleep(time_keep)
        # 松开（从后往前）
        for k in reversed(keys):
            keyboard.release(k)

    except Exception as e:
        print(f"按键失败 {key_str}: {e}")


def click_mouse( x: float, y: float, button: str="left", clicks: int = 1, interval: float = 0.1):
        """
        点击鼠标
        :param x: 点击位置的X坐标
        :param y: 点击位置的Y坐标
        :param button: 点击的鼠标按钮，默认左键
        :param clicks: 点击次数，默认1次
        :param interval: 每次点击间隔时间（秒），默认0.1秒
        """
        if button == "left":
            button = Button.left
        elif button == "right":
            button = Button.right
        elif button == "middle":
            button = Button.middle
        else:
            raise ValueError("无效的鼠标按钮")
        mouse.position = (x, y)
        for _ in range(clicks):
            mouse.press(button)
            time.sleep(interval)
            mouse.release(button)
            time.sleep(interval)

def mouse_scroll( x: float, y: float, delta_x: float = 0, delta_y: float = 0):
    """
    滚动鼠标
    :param x: 滚动位置的X坐标
    :param y: 滚动位置的Y坐标
    :param delta_x: 水平滚动量，默认0（不滚动）
    :param delta_y: 垂直滚动量，默认0（不滚动）
    """
    mouse.position = (x, y)
    time.sleep(0.3)
    mouse.scroll(delta_x, delta_y)